package com.lagou.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class EncodeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 类型向下转型
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
//        req.setCharacterEncoding("UTF-8");
        // 判断用户发出的请求是否是post请求，是，才设置编码
        if (req.getMethod().equalsIgnoreCase("post")){
            req.setCharacterEncoding("UTF-8");
        }

        resp.setContentType("text/html;charset=utf-8");
        chain.doFilter(req, resp);

    }

    @Override
    public void destroy() {
    }
}
